package com.sunmi.usercenter.ui.activity.fragment;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.sunmi.usercenter.Constant;
import com.sunmi.usercenter.R;
import com.sunmi.usercenter.bean.FmInfo;
import com.sunmi.usercenter.bean.Result;
import com.sunmi.usercenter.bean.Shop;
import com.sunmi.usercenter.bean.UserLoginInfo;
import com.sunmi.usercenter.bean.rpc.ReqLogin;
import com.sunmi.usercenter.ui.activity.HomeActivity;
import com.sunmi.usercenter.ui.component.LoadingDialog;
import com.sunmi.usercenter.ui.component.NetErrorDialog;
import com.sunmi.usercenter.ui.component.NetErrorDialog.TwoToDoOnClickListener;
import com.sunmi.usercenter.utils.MD5Utils;
import com.sunmi.usercenter.utils.NetWorkCenterUtils;

import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.lang.reflect.Type;

/**
 * 项目名称：Sunmi-User-Center
 * 类描述：登录商米账号的界面
 * 创建人：Abtswiath丶lxy
 * 创建时间：2016/6/7 11:33
 * 修改人：longx
 * 修改时间：2016/6/7 11:33
 * 修改备注：
 */
public class LoginFragment extends SuperFragment implements OnClickListener,TwoToDoOnClickListener{
	
	private View mView;
	private EditText mEditUsername;
	private EditText mEditPassword;
	private LinearLayout mLinShowPsd;
	private ImageView mImgEye;  
	private TextView mTxtError,mBtnLogin,mTxtForgetPsd,mTxtNewAccount;
	private RelativeLayout mRelBack;
	private boolean isHidden = true;//是否隐藏输入框文本
	private boolean editUsernameIsNull = true,editPasswordIsNull = true;
	private NetErrorDialog netErrorDialog;
	
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Shop shop = mCaCheModel.getShop();
		if(shop!=null){
			openFM(new FmInfo(UserAllInfoFragment.class, null));
		}else{
			initView();
		}
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		return mView = inflater.inflate(R.layout.fragment_login,container,false);
	}
	
	/**
	 * 初始化
	 */
	private void initView(){
		if(Constant.ME_IS_LAUNCHER){
			Constant.CLASS_FRAGMENT = Constant.StartRegisterFragment;
		}else{
			Constant.CLASS_FRAGMENT = Constant.DoubleClickExit;
		}
		mActivity.SetStatusColorf5f5f5();
		TextView mTxtTitle = (TextView) mView.findViewById(R.id.title);
		layoutTitle(mTxtTitle);
		
		mEditUsername = (EditText) mView.findViewById(R.id.txt_username);
		mEditPassword = (EditText) mView.findViewById(R.id.txt_password);
		mRelBack = (RelativeLayout) mView.findViewById(R.id.back);
		mLinShowPsd = (LinearLayout) mView.findViewById(R.id.ln_show_psd);
		mImgEye = (ImageView) mView.findViewById(R.id.img_eye);
		mTxtError = (TextView) mView.findViewById(R.id.txt_error);
		mBtnLogin = (TextView) mView.findViewById(R.id.btn_login);
		mTxtForgetPsd = (TextView) mView.findViewById(R.id.txt_forget_pad);
		mTxtNewAccount = (TextView) mView.findViewById(R.id.txt_new_account);
		mRelBack.setOnClickListener(this);
		mLinShowPsd.setOnClickListener(this);
		mBtnLogin.setOnClickListener(this);
		mTxtForgetPsd.setOnClickListener(this);
		mTxtNewAccount.setOnClickListener(this);
		if(!Constant.ME_IS_LAUNCHER){
			mRelBack.setVisibility(View.GONE);
		}
		mBtnLogin.setBackgroundResource(R.drawable.btn_bg_no_click2);
		mBtnLogin.setEnabled(false);
//		UserLoginInfo info = mCaCheModel.readUserPasswordAndUsername();
//		if(info!=null){
//			if(info.getUsername().length()>0){
//				mEditUsername.setText(info.getUsername());
//				editUsernameIsNull = false;
//			}
//			if(info.getPassword().length()>0){
//				mEditPassword.setText(info.getPassword());
//				editPasswordIsNull = false;
//			}
//			changeLoginBtn();
//		}
		editChangeListenter();
	}
	
	
	/**
	 * 是否显示文本框的内容
	 */
	private void showPsdOrHidePsd(){
		if(isHidden){
			mEditPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
			mImgEye.setBackgroundResource(R.drawable.eye_yes);
		}else{
			mEditPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
			mImgEye.setBackgroundResource(R.drawable.eye_no);
		}
		isHidden = !isHidden;
		mEditPassword.postInvalidate();
		//切换后将EditText光标置于末尾
        CharSequence charSequence = mEditPassword.getText();
        if (charSequence instanceof Spannable) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }
	}
	
	private void login(){
		if(!NetWorkCenterUtils.isNetworkConnected(getActivity())){
			netErrorDialog = NetErrorDialog.createDialog(getActivity(), this);
			netErrorDialog.show();
		}
		final LoadingDialog mLoadingDialog = LoadingDialog.createDialog(getActivity(), getString(R.string.logining));
		mLoadingDialog.show();
		final String username = mEditUsername.getText().toString().trim();
		final String password = mEditPassword.getText().toString();
		ReqLogin reqLogin = new ReqLogin();
		reqLogin.setPassword(MD5Utils.md5Password(username, password));
		reqLogin.setUserName(username);
		mHttpController.login(reqLogin, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				String json = new String(arg2);
				Gson gson = new Gson();
				Type type = new TypeToken<Result<Shop>>(){}.getType();
				Result<Shop> result = null;
				try {
					result = gson.fromJson(json,type);
				}catch (Exception e){
					e.printStackTrace();
				}
				if(result!=null&&result.getCode()==1){
					showToast("登录成功！");
					if(result.data!=null){
						mCaCheModel.saveShop(result.data);
					}
					UserLoginInfo userLoginInfo = new UserLoginInfo();
					userLoginInfo.setPassword(password);
					userLoginInfo.setUsername(username);
//					mCaCheModel.saveUserPasswordAndUsername(userLoginInfo);
					if(Constant.ME_IS_LAUNCHER){
						exitMe();
						getActivity().finish();
					}else{
						openFM(new FmInfo(UserAllInfoFragment.class, null));
					}
				}else{
					mTxtError.setVisibility(View.VISIBLE);
				}
				mLoadingDialog.dismiss();
			}
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				mLoadingDialog.dismiss();
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			openFM(new FmInfo(StartRegisterFragment.class, null));
			break;
		case R.id.ln_show_psd:
			showPsdOrHidePsd();
			break;
		case R.id.btn_login:
			login();
			break;
		case R.id.txt_forget_pad:
			openFM(new FmInfo(RetrievePsdFragment.class, null));
			break;
		case R.id.txt_new_account:
			Constant.mInputToCode.setFramgmentCode(1);
			openFM(new FmInfo(RegisterFragment.class, null));
			break;
		default:
			break;
		}
	}
	
	private void editChangeListenter(){
		mEditPassword.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			@Override
			public void afterTextChanged(Editable s) {
				editPasswordIsNull = s.length()==0;
				changeLoginBtn();
			}
		});
		mEditUsername.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			@Override
			public void afterTextChanged(Editable s) {
				editUsernameIsNull = s.length()==0;
				changeLoginBtn();
			}
		});
	}
	
	private void changeLoginBtn(){
		if(!editPasswordIsNull&&!editUsernameIsNull){
			mBtnLogin.setBackgroundResource(R.drawable.btn_bg);
			mBtnLogin.setEnabled(true);
		}else{
			mBtnLogin.setBackgroundResource(R.drawable.btn_bg_no_click2);
			mBtnLogin.setEnabled(false);
		}
	}

	@Override
	public void changNet() {
		intentWifi();
	}

	@Override
	public void ok() {
		netErrorDialog.dismiss();
	}
   
}
